package com.gxh.controller.admin;

import com.gxh.constant.MessageConstant;
import com.gxh.result.Result;
import com.gxh.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/common")
@Slf4j
@Api(tags = "通用接口")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 上传多张图片（去重）
     */
    @PostMapping("/upload/images")
    @ApiOperation("上传多张图片（自动去重）")
    public Result<List<String>> uploadImages(@RequestParam("files") MultipartFile[] files) {
        log.info("上传图片文件：{}", (Object) files);

        List<String> filePaths = new ArrayList<>();

        try {
            for (MultipartFile file : files) {
                if (file.isEmpty()) continue;

                byte[] fileBytes = file.getBytes();
                String extension = getExtension(file.getOriginalFilename());
                String fileMd5 = DigestUtils.md5Hex(fileBytes);
                String objectName = MessageConstant.IMAGE_DIR + fileMd5 + extension;

                if (!aliOssUtil.doesObjectExist(objectName)) {
                    aliOssUtil.upload(fileBytes, objectName);
                }

                filePaths.add(aliOssUtil.getFileUrl(objectName));
            }

            if (filePaths.isEmpty()) {
                return Result.error("上传失败，文件为空");
            }
            log.info("上传成功，文件路径：{}", filePaths);
            return Result.success(filePaths);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }

    /**
     * 上传多个视频（去重）
     */
    @PostMapping("/upload/videos")
    @ApiOperation("上传多个视频（自动去重）")
    public Result<List<String>> uploadVideos(@RequestParam("files") MultipartFile[] files) {
        log.info("上传视频文件：{}", (Object) files);

        List<String> videoPaths = new ArrayList<>();

        try {
            for (MultipartFile file : files) {
                if (file.isEmpty()) continue;

                byte[] fileBytes = file.getBytes();
                String extension = getExtension(file.getOriginalFilename());
                String fileMd5 = DigestUtils.md5Hex(fileBytes);
                String objectName = MessageConstant.VIDEO_DIR + fileMd5 + extension;

                if (!aliOssUtil.doesObjectExist(objectName)) {
                    aliOssUtil.upload(fileBytes, objectName);
                }

                videoPaths.add(aliOssUtil.getFileUrl(objectName));
            }

            if (videoPaths.isEmpty()) {
                return Result.error("上传失败，视频为空");
            }

            return Result.success(videoPaths);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }

    /**
     * 上传封面图（去重）
     */
    @PostMapping("/upload/cover")
    @ApiOperation("上传视频封面图（自动去重）")
    public Result<String> uploadCover(@RequestParam("files") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("封面图为空");
        }

        try {
            byte[] fileBytes = file.getBytes();
            String extension = getExtension(file.getOriginalFilename());
            String fileMd5 = DigestUtils.md5Hex(fileBytes);
            String objectName = MessageConstant.COVER_DIR + fileMd5 + extension;

            if (!aliOssUtil.doesObjectExist(objectName)) {
                aliOssUtil.upload(fileBytes, objectName);
            }

            return Result.success(aliOssUtil.getFileUrl(objectName));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("封面图上传失败");
        }
    }

    /**
     * 工具：获取文件扩展名（包含 .）
     */
    private String getExtension(String filename) {
        int dotIndex = filename.lastIndexOf('.');
        return dotIndex >= 0 ? filename.substring(dotIndex) : "";
    }
}
